<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.title" placeholder="请输入名称" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" /> -->
      <!-- <el-button v-waves class="filter-item" type="primary" icon="el-icon-search">
        {{ $t('table.search') }}
      </el-button> -->
      <el-radio-group v-model="radio1" @change="change">

        <el-radio-button label="2">可发布</el-radio-button>
        <el-radio-button label="4">发布失败</el-radio-button>
        <el-radio-button label="3">已发布</el-radio-button>
        <!-- <el-radio-button label="0">全部</el-radio-button> -->
      </el-radio-group>
      <el-button v-show="radio1==2||radio1==4" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="open">
        发布
      </el-button>

      <el-button type="danger" @click="handleDeleteAll()">
        {{ $t('table.delete') }}
      </el-button>

    </div>
    <el-table v-loading="listLoading" :data="list" border fit highlight-current-row style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column align="center" label="ID" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.article_id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="300px" label="标题">
        <template slot-scope="{row}">
          <router-link v-if="radio1==2" :to="'/example/edit/'+row.article_id" class="link-type">
            <span>{{ row.title }}</span>
          </router-link>
          <span v-else>{{ row.title }}</span>

        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="内容">
        <template slot-scope="scope">
          <span>{{ scope.row.content }}</span>
        </template>
      </el-table-column>

      <el-table-column class-name="status-col" label="发布状态" width="110">
        <template slot-scope="{row}">
          <el-tag v-if="row.is_fabu==1">
            生成中
          </el-tag>
          <el-tag v-if="row.is_fabu==2">
            可发布
          </el-tag>
          <el-tag v-if="row.is_fabu==3">
            发布
          </el-tag>
          <el-tag v-if="row.is_fabu==4">
            发布失败
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column width="180px" align="center" label="比特ID">
        <template slot-scope="scope">
          {{ scope.row.envId }}
          <!-- <el-select v-model="scope.row.envId" placeholder="请选择">
            <el-option
              v-for="item in list2"
              :key="item.value"

              :label="item.remark"
              :value="item.id"
            />
          </el-select> -->
        </template>
      </el-table-column>
      <el-table-column width="120px" align="center" label="时间">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="120">
        <template slot-scope="scope">

          <el-button type="primary" size="small" @click="edit(scope.row)">
            编辑
          </el-button>
          <!-- <el-button v-if="scope.row.is_fabu==3" size="mini" type="danger" @click="handleDelete([scope.row])">
            {{ $t('table.delete') }}
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog
      title="发布"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div>
        <el-table
          :data="multipleSelection"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange2"
        >
          <el-table-column align="center" label="ID" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.article_id }}</span>
            </template>
          </el-table-column>
          <el-table-column min-width="300px" label="标题">
            <template slot-scope="{row}">
              <router-link v-if="radio1==2" :to="'/example/edit/'+row.article_id" class="link-type">
                <span>{{ row.title }}</span>
              </router-link>
              <span v-else>{{ row.title }}</span>

            </template>
          </el-table-column>

          <!-- <el-table-column width="180px" align="center" label="内容">
            <template slot-scope="scope">
              <span>{{ scope.row.content }}</span>
            </template>
          </el-table-column> -->

          <el-table-column width="180px" align="center" label="比特账号">
            <template slot-scope="scope">
              <!-- {{ scope.row.envId }} -->
              <el-select v-model="scope.row.envId" placeholder="请选择">
                <el-option
                  v-for="item in list2"
                  :key="item.value"

                  :label="item.remark"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>

        </el-table>
        <!-- <el-table
          :data="list2"
          border
          fit
          highlight-current-row
          style="width: 100%;"
          @selection-change="handleSelectionChange2"
        >
          <el-table-column
            type="selection"
            width="55"
          />
          <el-table-column :label="'ID'" prop="id" sortable="custom" align="center" width="180">
            <template slot-scope="{row}">
              <span>{{ row.id }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账号名称" min-width="150px">
            <template slot-scope="{row}">
              <span class="link-type">{{ row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="账号IP" min-width="150px">
            <template slot-scope="{row}">
              <span>{{ row.host }}</span>
            </template>
          </el-table-column>
          <el-table-column label="用户名称" min-width="150px">
            <template slot-scope="{row}">
              <span>{{ row.remark }}</span>
            </template>
          </el-table-column>

        </el-table> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-date-picker
          v-model="value1"
          style="margin-right:20px;"
          type="datetime"
          placeholder="选择日期时间"
        />
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleCreate">一键发布</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="pathVisible"
      width="30%"
      @close="pathClose"
    >
      <span>{{ articlePath }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="pathVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-document" @click="handleCopy(articlePath,$event)">
          复制
        </el-button>
        <!-- <el-button type="primary" @click="pathVisible = false">确 定</el-button> -->
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getwzlist, autoSend, browserList, download, fb, btid, scwz, path, unlink } from '@/api/article'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import { getToken } from '@/utils/auth'
import clip from '@/utils/clipboard' // use clipboard directly
export default {
  name: 'ArticleList',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      pathVisible: false,
      value1: '',
      radio1: '2',
      list: null,
      list2: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20
      },
      multipleSelection: [],
      multipleSelection2: [],
      dialogVisible: false,
      dir: 'D:\\web\\ddd',
      articlePath: ''
    }
  },
  created() {
    this.getList()
    this.getList2()
    this.path()
  },
  methods: {
    handleDeleteAll() {
      if (this.multipleSelection.length > 0) {
        this.handleDelete(this.multipleSelection)
      } else {
        this.$notify({
          title: '提示',
          message: '请选择文章',
          type: 'success',
          duration: 2000
        })
      }
    },
    pathClose() {
      this.articlePath = ''
    },
    handleCopy(text, event) {
      clip(text, event)
    },
    async edit(item) {
      const url = 'http://' + item.content
      const dir = this.dir
      const name = item.article_id + '.docx'
      const data = {
        url,
        dir,
        name
      }
      const res = await download(data)
      if (res.code === 200) {
        this.articlePath = res.data
        this.pathVisible = true
      }
    },
    async path() {
      const res = await path()
      if (res.code === 200) {
        this.dir = res.data
      }
      console.log(res)
    },
    unlink(path) {
      unlink({ path })
    },
    handleDelete(row) {
      const data = row.map((item) => {
        const { article_id, content } = item
        return { article_id, content }
      })
      scwz(data).then(response => {
        if (response.code === 200) {
          // 删除本地文件
          data.forEach((item) => {
            const name = item.article_id + '.docx'
            this.unlink(this.dir + '//' + name)
          })

          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        } else {
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'error',
            duration: 2000
          })
        }
      })
    },
    change(e) {
      this.getList()
    },
    handleClose(done) {
      this.dialogVisible = false
    },
    handleSelectionChange(val) {
      console.log({ val })
      this.multipleSelection = val
    },
    handleSelectionChange2(val) {
      console.log({ val })
      this.multipleSelection2 = val
    },
    open() {
      if (this.multipleSelection.length > 0) {
        const length = this.list2.length
        // 自动选择比特浏览id
        if (this.radio1 === '2') {
          this.multipleSelection = this.multipleSelection.map((item, index) => {
            if (length > index) {
              item.envId = this.list2[index]['id']
            }
            return item
          })
        }

        this.dialogVisible = true
      } else {
        this.$notify({
          title: '提示',
          message: '请选择文章',
          type: 'success',
          duration: 2000
        })
      }
    },
    async handleCreate() {
      // this.multipleSelection2.forEach((item2) => {
      // this.multipleSelection.forEach(async(item) => {
      for (const item of this.multipleSelection) {
        const url = 'http://' + item.content

        const dir = this.dir
        const name = item.article_id + '.docx'
        const data = {
          url,
          dir,
          name
        }
        const res = await download(data)
        console.log(res)
        // 选定比特浏览器id才能发布
        if (item.envId) {
          // 文章绑定发布者
          btid([{ article_id: item.article_id, envId: item.envId }])
          const response = await autoSend({ path: `${dir}\\${name}`, envId: item.envId, time: this.value1, article_id: item.article_id })
          if (this.value1) {
            this.$notify({
              title: '成功',
              message: response.msg,
              type: 'success',
              duration: 2000
            })
            // this.getList()
            this.dialogVisible = false
          } else {
            if (response.code === 200) {
              await fb({ article_id: item.article_id, state: 0, bt_id: item.envId })
              this.$notify({
                title: '成功',
                message: '发布成功',
                type: 'success',
                duration: 2000
              })

              this.dialogVisible = false
            } else {
              await fb({ article_id: item.article_id, state: 1, bt_id: item.envId })
              this.$notify({
                title: '失败',
                message: '发布失败',
                type: 'error',
                duration: 2000
              })
            }
          }

          console.log('this.response', response)
        }
      }
      this.getList()
      // })
    },
    // async handleCreate() {
    //   // const url = 'http://' + '118.89.77.89/22024061421304221.docx'
    //   // const dir = 'D:\\web\\waibao\\media-admin-server\\头条自动发布\\word'
    //   // const name = 'gggg' + '.docx'
    //   // const data = {
    //   //   url: 'http://127.0.0.1:3001/demo.docx',
    //   //   // url,
    //   //   dir,
    //   //   name
    //   // }
    //   // const res = await download(data)
    //   // console.log(res)
    //   // autoSend({ path: `${dir}\\${name}`, envId: 'b4daff928b9a4a9da4a6b8d34956ab7c' }).then(response => {
    //   //   console.log('this.response', response)
    //   // })
    //   // return
    //   this.multipleSelection2.forEach((item2) => {
    //     this.multipleSelection.forEach(async(item) => {
    //       // .replace(/\\/g, '\\\\')
    //       // const url = 'http://' + '118.89.77.89/22024061421304221.docx'
    //       const url = 'http://' + item.content

    //       const dir = this.dir
    //       const name = item.article_id + '.docx'
    //       const data = {
    //         // url: 'http://127.0.0.1:3001/demo.docx',
    //         url,
    //         dir,
    //         name
    //       }
    //       const res = await download(data)
    //       console.log(res)
    //       // 文章绑定发布者
    //       btid([{ article_id: item.article_id, envId: item2.id }])

    //       autoSend({ path: `${dir}\\${name}`, envId: item2.id, time: this.value1 }).then(async response => {
    //         if (response.code === 200) {
    //           await fb({ article_id: item.article_id })
    //           this.$notify({
    //             title: '成功',
    //             message: '发布成功',
    //             type: 'success',
    //             duration: 2000
    //           })
    //           this.getList()
    //           this.dialogVisible = false
    //         } else {
    //           this.$notify({
    //             title: '失败',
    //             message: '发布失败',
    //             type: 'error',
    //             duration: 2000
    //           })
    //         }
    //         console.log('this.response', response)
    //       })
    //     })
    //   })
    //   // autoSend({ path: `D:\\web\\waibao\\media-admin-server\\头条自动发布\\word\\22024061323101021.docx`, envId: 'b4daff928b9a4a9da4a6b8d34956ab7c' }).then(response => {
    //   //   console.log('this.response', response)
    //   // })
    // },
    getList2() {
      this.listLoading2 = true
      browserList({ page: 0,
        pageSize: 100 }).then(response => {
        console.log({ response })

        if (response.success) {
          console.log(888999)
          const list = response.data.list
          const arr = []
          console.log({ list })
          list.forEach((item) => {
            if (item.platform === 'https://www.toutiao.com/') {
              arr.push({ id: item.id, name: item.name, host: item.lastIp, remark: item.remark })
            }
          })
          this.list2 = arr
          console.log('this.list', this.list2)
        } else {
          this.$notify({
            title: '失败',
            message: '比特浏览器' + response.msg,
            type: 'error',
            duration: 2000
          })
        }

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading2 = false
        }, 1.5 * 1000)
      })
    },
    getList() {
      this.listLoading = true
      getwzlist({ user_id: getToken(), is_fabu: this.radio1 }).then(response => {
        this.list = response.data
        // this.total = response.data.total
        this.listLoading = false
      })
    }
  }
}
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
